from datetime import datetime
from app.db import db

# 5. 订单表: b_order
class BOrder(db.Model):
    __tablename__ = 'b_order'

    status = db.Column(db.String(2), nullable=False, comment='订单状态(如01-待支付､02-已完成,需枚举)')
    order_time = db.Column(db.DateTime(6), nullable=False, default=datetime.utcnow, comment='下单时间')
    pay_time = db.Column(db.DateTime(6), comment='支付时间(为空表示未支付)')
    thing_id = db.Column(db.BigInteger, db.ForeignKey('b_thing.id'), nullable=False,
                         comment='关联物品ID(外键,关联b_thing)')
    user_id = db.Column('userId', db.BigInteger, db.ForeignKey('b_user.id'), nullable=False,
                        comment='关联用户ID(外键,关联b_user)')
    count = db.Column(db.Integer, nullable=False, comment='购买数量')
    order_number = db.Column(db.String(13), unique=True, nullable=False, comment='订单号(唯一标识,如202408010001)')
    receiver_address = db.Column(db.String(50), nullable=False, comment='收货地址')
    receiver_name = db.Column(db.String(20), nullable=False, comment='收货人姓名')
    receiver_phone = db.Column(db.String(20), nullable=False, comment='收货人电话')
    remark = db.Column(db.String(30), comment='订单备注')
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='订单唯一主键ID')

    def to_dict(self):
        return {
            'id': self.id,
            'status': self.status,
            'order_time': self.order_time.isoformat() if self.order_time else None,
            'pay_time': self.pay_time.isoformat() if self.pay_time else None,
            'thing_id': self.thing_id,
            'user_id': self.user_id,
            'count': self.count,
            'order_number': self.order_number,
            'receiver_address': self.receiver_address,
            'receiver_name': self.receiver_name,
            'receiver_phone': self.receiver_phone,
            'remark': self.remark
        }